package com.zkq.graduate.controller;

import com.zkq.graduate.pojo.Role;
import com.zkq.graduate.pojo.Users;
import com.zkq.graduate.service.UserAndRoleService;
import com.zkq.graduate.util.CookieAndSessionUtil;
import com.zkq.graduate.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author zhangkaiqiang
 * @Date 2020/1/14  19:52
 * @Description TODO
 */
@Controller
@Slf4j
@Api(tags = "路由转发控制类")
public class RouteController {


	@Resource(name = "userAndRoleService")
	private UserAndRoleService userAndRoleService;


	@GetMapping("/login.html")
	@ApiOperation(value = "跳转到登录页面",notes = "校验token有效时直接调转到后台主页")
	public String toLoginPage(HttpServletRequest request, HttpServletResponse response){
		Cookie[] cookies=request.getCookies();
		Map<String,Object> verifyResultMap=new HashMap<>(16);
		if(cookies==null){
			return "login";
		}
		for (Cookie cookie : cookies) {
			if(Objects.equals("token",cookie.getName())){
				String token=cookie.getValue();
				if(StringUtils.isNotBlank(token)){
					// 验证客户端携带的token,若token有效,直接进入主页
					verifyResultMap= JwtUtil.verifyJwt(token);
					if(verifyResultMap!=null){
						String account= (String) verifyResultMap.get("account");
						request.setAttribute("id",verifyResultMap.get("id"));
						request.setAttribute("account",account);
						// 得到用户的角色信息
						Users users=Users.builder()
								.account(account)
								.build();
						List<Role> roleList=userAndRoleService.findRoleByUser(users);
						request.setAttribute("role",roleList);
						log.info(account+"login in");
						JwtUtil.refreshToken(request,response,verifyResultMap);
						log.info(account+">>>>>>登录了系统");
						return "main";
					}
				}
			}
		}
		return "login";
	}


	@GetMapping("/toMainPage")
	@ApiOperation(value = "登录以后跳转到主页")
	public String toMainPage(){
		return "main";
	}


	@GetMapping("/logout")
	@ApiOperation(value = "用户退出")
	public String logout(HttpServletRequest request,HttpServletResponse response){
		CookieAndSessionUtil.clearCookie(request,response,"token");
		return "redirect:/login.html";
	}
}
